import 'dart:convert';
import 'dart:io';
import 'dart:ui';
import 'package:flutter/services.dart';
import 'package:flutter_widget_from_html/flutter_widget_from_html.dart';
import 'package:package_info/package_info.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:wallet_utils/dialog/update_dialog.dart';
import 'package:wallet_utils/log_util.dart';
import 'package:wallet_utils/login_utils.dart';
import 'package:wallet_utils/report_widget/base/callback/base_callback.dart';
import 'package:wallet_utils/text_style.dart';
import 'package:wallet_utils/base_router_config.dart';
import 'package:url_launcher/url_launcher.dart';
import 'agreement_dialog.dart';
import 'mine/api/mine_api.dart';
import 'mine/bean/aboutUsBean.dart';

class StartPage extends StatefulWidget {
  const StartPage({Key? key}) : super(key: key);

  @override
  _StartPageState createState() => _StartPageState();
}

class _StartPageState extends State<StartPage> {
  @override
  void initState() {
    super.initState();
    // showLeading();
    showLeading();
  }

  Future<Null> goHome() {
    return LoginUtils.isLogin().then((value) {
      Future.delayed(const Duration(milliseconds: 1000), () {
        // 不要使用Navigator.of(context).pushReplacement方法包裹一个MaterialPageRoute的方式来跳转
        // 会导致第一个页面被认定为MaterialPageRoute而不是一个GetPageRoute
        // 最终Get.offAllNamed的时候路由栈第一个页面无法释放
        if (value) {
          Get.offNamed(BaseRouterConfig.main);
        } else {
          Get.offNamed(BaseRouterConfig.main);
          // Get.offNamed(BaseRouterConfig.main);
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(BoxConstraints(maxWidth: MediaQuery.of(context).size.width, maxHeight: MediaQuery.of(context).size.height),
        context: context, designSize: const Size(375, 812), orientation: Orientation.portrait);

    return Scaffold(
      body: Container(
        color: Colors.white,
        child: SizedBox(
          child: Image.asset(
            'images/icon_splash.png',
            fit: BoxFit.cover,
          ),
        ),
      ),
    );
  }

  showLeading() {
    LoginUtils.getAgreementBool().then((value) {
      if (value) {
        rootBundle.loadString('assets/privacy.json').then((address) {
          var data = json.decode(address);
          aboutUsInfo dataInfo=aboutUsInfo.fromJson(data);
          String? name = dataInfo.name;
          String? content = dataInfo.content;
          Future.delayed(Duration.zero, showAgreementDialog(name, content));
        });

        // getUserInfo(ContentType.privacyPolicy);
      } else {
        checkVersion();
      }
    });
  }

  showAgreementDialog(String? name, String? content) {
    LoginUtils.getAgreementBool().then((value) {
      if (value) {
        // LoginUtils.saveAgreementBool(false).then((value){
        //   ;
        // });
        Future.delayed(Duration.zero, () {
          showDialog<Null>(
            context: context,
            barrierDismissible: false,
            useSafeArea: false,
            useRootNavigator: false,
            builder: (BuildContext context) {
              return AgreementDialog(
                  name: '隐私协议',
                  content: content,
                  isCloseBt: true,
                  onTap: () {
                    LoginUtils.saveAgreementBool(false);
                    Navigator.pop(context);
                    checkVersion();
                  });
            },
          );
        });
      }
    });
  }

  //forceUpdateFlag 1强制更新 2不强制更新 可取消 3没有更新
  checkVersion() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String? version = packageInfo.version;
    await MineApi.getAppVersion(
        version,
        BaseCallback(onSuccess: (map) {
          String latestApkUrl='';
          int forceUpdateFlag = map['data']['forceUpdateFlag'];
          String content = map['data']['content'];
          String appVersion = map['data']['appVersion'];
          if(map['data']['latestApkUrl']!=null){
            latestApkUrl = map['data']['latestApkUrl'];
          }
          // if(haveNewVersion(appVersion,version)){
          //   showDialog(
          //       barrierDismissible: false,
          //       context: context,
          //       builder: (context) {
          //         return forceUpdateFlag == 1
          //             ? WillPopScope(
          //           onWillPop: _requestPop,
          //           child: UpdateDialog(
          //             isShow: false,
          //             tipsTitle: '更新内容',
          //             content: Container(
          //               width: 200,
          //               alignment: Alignment.center,
          //               child: HtmlWidget(
          //                 content,
          //                 textStyle: TextStyleUtils.style000000(fontSize: 13.sp),
          //               ),
          //             ),
          //             yesStr: '立即升级',
          //             yesCallback: () {
          //               if (Platform.isAndroid) {
          //                 launch(latestApkUrl);
          //               } else {
          //                 // LaunchUtils.launchUrl("https://itunes.apple.com/app/id1435265996");
          //               }
          //             },
          //           ),
          //         )
          //             : UpdateDialog(
          //           isShow: true,
          //           content: Container(
          //             width: 200,
          //             alignment: Alignment.center,
          //             child: HtmlWidget(
          //               content,
          //               textStyle: TextStyleUtils.style000000(fontSize: 13.sp),
          //             ),
          //           ),
          //           tipsTitle: '更新内容',
          //           yesCallback: () {
          //             if (Platform.isAndroid) {
          //               launch(latestApkUrl);
          //             } else {
          //               // LaunchUtils.launchUrl("https://itunes.apple.com/app/id1435265996");
          //             }
          //           },
          //           yesStr: '立即升级',
          //           noStr: '取消',
          //           noCallback: () {
          //             Get.back();
          //             goHome();
          //           },
          //         );
          //       });
          // }else{
          //   goHome();
          // }
          // if (forceUpdateFlag == 3) {
          //   goHome();
          // } else {
          // }
          goHome();

        }, onError: (error) {
          // ToastUtils.showToast(error ?? '');
          goHome();
        }));
  }

  bool haveNewVersion(String newVersion, String old) {
    if (newVersion == null || newVersion.isEmpty || old == null || old.isEmpty) {
      return false;
    }
    int newVersionInt, oldVersion;
    var newList = newVersion.split('.');
    var oldList = old.split('.');
    if (newList.isEmpty || oldList.isEmpty) {
      return false;
    }
    for (int i = 0; i < newList.length; i++) {
      newVersionInt = int.parse(newList[i]);
      oldVersion = int.parse(oldList[i]);
      LogUtils.d("版本号比对这$newVersionInt  $oldVersion  $old");
      if (newVersionInt > oldVersion) {
        return true;
      } else if (newVersionInt < oldVersion) {
        return false;
      }
    }

    return false;
  }

  Future<bool> _requestPop() {
    return Future.value(false);
  }
}
